# 完成基本内容的封装，比如初始化driver，find, find and click
import logging

from appium.webdriver.webdriver import WebDriver
from selenium.common.exceptions import NoSuchElementException

logger = logging.getLogger()

class BasePage:
    def __init__(self,driver:WebDriver=None):
        self.driver = driver

    def find(self, by, value):
        logger.info("find")
        logger.info(by)
        logger.info(value)
        return self.driver.find_element(by, value)

    def swipe_find(self,by, value,num=3):
        logger.info("swipe_find")
        # 设置一个最大的查找次数
        for i in range(num):
            if i == num -1:
                raise NoSuchElementException(f'找了{num - 1}次，未找到')
            try:
                return self.driver.find_element(by,value)
            except:
                # 如果未找到这个元素，捕获这个异常，并且滑动一屏
                print("未找到")
                # 滑动
                size = self.driver.get_window_size()
                width = size.get('width')
                height = size.get('height')
                start_x = width / 2
                start_y = height * 0.8
                end_x = start_x
                end_y = height * 0.2
                duration = 2000
                self.driver.swipe(start_x, start_y, end_x, end_y, duration)

    def swipe_find_and_click(self,by,value):
        logger.info("swipe_find_and_click")
        self.swipe_find(by,value).click()

    def finds(self, by, value):
        logger.info("finds")
        return self.driver.find_elements(by, value)

    def find_and_click(self, by, value):
        logger.info("find_and_click")
        self.find(by,value).click()

    def find_and_send(self, by, value, text):
        logger.info("find_and_send")
        self.find(by, value).send_keys(text)

    def back_main(self,num=3):
        for i in range(0,num):
            logger.info("back_main")
            self.driver.back()
